package com.wxtt.android.common;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.fast.dev.frame.http.HttpTaskKey;
import com.fast.dev.frame.ui.SupportFragment;
import com.wxtt.android.dialog.TipDialog;

/**
 * 说明：Fragment基类(懒加载)
 * <p/>
 * 作者：fanly
 * <p/>
 * 时间：2016/1/3 0:52
 * <p/>
 * 版本：verson 1.0
 */
public abstract class CommonFragment extends SupportFragment implements HttpTaskKey {

    protected CommonActivity mActivity;
    protected final String HTTP_TASK_KEY = "key_" + hashCode();

    //懒加载
    private boolean isFirstResume = true;
    private boolean isFirstVisible = true;
    private boolean isFirstInvisible = true;
    private boolean isPrepared = false;

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        return inflater.inflate(setRootView(),null);
    }

    protected abstract int setRootView();

    @Override
    public String getHttpTaskKey() {
        return HTTP_TASK_KEY;
    }

    private synchronized void initPrepare(){
        if (isPrepared){
            onFirstUserVisible();
        }else {
            isPrepared = true;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getActivity() instanceof CommonActivity) {
            mActivity = (CommonActivity) getActivity();
        } else {
            throw new RuntimeException("must extends CommonActivity!");
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initPrepare();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isFirstResume){
            isFirstResume = false;
            return;
        }
        if (getUserVisibleHint()){
            onUserVisible();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getUserVisibleHint()){
            onUserInvisible();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser){
            if (isFirstVisible){
                isFirstVisible = false;
                initPrepare();
            }else {
                onUserVisible();
            }
        }else {
            if (isFirstInvisible){
                isFirstInvisible = false;
                onFirstUserInvisible();
            }else {
                onUserInvisible();
            }
        }
    }

    /**
     * 说明：Fragment第一次显示调用
     */
    public void onFirstUserVisible(){}

    /**
     * 说明：Fragment第一次隐藏调用
     */
    public void onFirstUserInvisible(){}

    /**
     * 说明：Fragment显示调用
     */
    public void onUserVisible(){}

    /**
     * 说明：Fragment隐藏调用
     */
    public void onUserInvisible(){}

}
